<?php
namespace App\Lib;

/**
 * 数据库操作辅助类，对PDO进行了基本的封装
 * @package App\Lib
 */
abstract class Model
{
    private $dbConfig;

    protected $table = '';

    protected $pk = 'id';

    public function __construct()
    {
        $this->dbConfig = require CONFIG_DIR . DIRECTORY_SEPARATOR . 'db.php';
    }

    /**
     * 根据主键获取单个记录，返回一个单一的实体对象
     *
     * @param $pk
     */
    public static function find($pk)
    {
        $obj = new static();
        $sql = 'select * from' . ' ' . $obj->table . ' ' . 'where' . ' ' . $obj->pk . '=?';
        $params = [$pk];
        $data = $obj->query($sql, $params);
        if (count($data) > 0) {
            return $data[0];
        }
        return null;
    }

    /**
     * 根据查询条件查询多个数据记录
     *
     * @param string $where
     * @param array $params
     * @return mixed
     */
    public static function get($where = '', $params = [])
    {
        $obj = new static();
        $sql = 'select * from' . ' ' . $obj->table;
        if (!empty($where)) {
            $sql .= ' ' . 'where' . ' ' . $where;
        }
        return $obj->query($sql, $params);
    }

    public function delete($pk)
    {
        //
    }

    /**
     * 执行增删改SQL语句
     *
     * @param $sql
     * @param array $params 预处理语句参数按顺序构成的数组
     * @return true表示语句执行成功
     */
    public function execute($sql, $params = [])
    {
        try {
            $dsn = 'mysql:host=' . $this->dbConfig['host'] . ';dbname=' . $this->dbConfig['db'];
            $conn = new \PDO($dsn, $this->dbConfig['username'], $this->dbConfig['password']);
            $stmt = $conn->prepare($sql);
            for ($i = 0; $i < count($params); $i++) {
                $stmt->bindParam($i + 1, $params[$i]);
            }
            if ($stmt->execute()) {
                return true;
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return false;
    }

    /**
     * 执行SQL查询语句
     *
     * @param $sql
     * @param array $params 预处理语句参数按顺序构成的数组
     * @return array 返回包含查询结果数据的数组
     */
    public function query($sql, $params = [])
    {
        $data = [];
        try {
            $dsn = 'mysql:host=' . $this->dbConfig['host'] . ';dbname=' . $this->dbConfig['db'];
            $conn = new \PDO($dsn, $this->dbConfig['username'], $this->dbConfig['password']);
            $stmt = $conn->prepare($sql);
            for ($i = 0; $i < count($params); $i++) {
                $stmt->bindParam($i + 1, $params[$i]);
            }
            if ($stmt->execute()) {
                while ($obj = $stmt->fetchObject(get_called_class())) {
                    array_push($data, $obj);
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return $data;
    }
}
